package com.itheima.interceptors;

import cn.hutool.core.util.StrUtil;
import com.itheima.utils.JwtUtils;
import com.itheima.utils.ThreadLocalUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * @Author:篍
 * @Date: 2025/07/17 16:16
 * @Description:
 */
@Component
public class AuthorizedInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object handler) throws Exception {
        //获取token
        String token = httpServletRequest.getHeader("token");
        //token为空
        if (StrUtil.isBlank(token)){
            httpServletResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return false;
        }
        //不为空,校验token
        try {
            Claims claims = JwtUtils.parseJWT(token);
            Object id = claims.get("id");
            ThreadLocalUtils.setId((Integer) id);
            System.out.println(id);
            //放行
            return true;
        } catch (Exception e) {
            //非法token
            httpServletResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return false;
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        ThreadLocalUtils.remove();
    }
}
